using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace LynxWebLog.Areas.Pages
{
    public class PagesAreaAreaRegistration : AreaRegistration 
	{
        public override string AreaName 
		{
            get 
			{
                return "Pages";
            }
        }

public override void RegisterArea(AreaRegistrationContext context) 
		{
            context.MapRoute(
                name: "Pages_CurrentDisplay",
                url: "Pages/{username}/{blogname}",
                defaults: new { controller = "Page", action = "ViewPage" },
                constraints: new
                {
                    username = new PageOwnerRouteConstraint(),
                    blogname = new PageNameRouteConstraint()
                }
            );

            context.MapRoute(
                "Pages_default",
                "Pages/{username}/{blogname}/{controller}/{action}/{id}",
                defaults: new { action = "Index", id = UrlParameter.Optional },
                constraints: new
                {
                    username = new PageOwnerRouteConstraint(),
                    blogname = new PageNameRouteConstraint()
                }
            );
        }
    }

    public class PageOwnerRouteConstraint : IRouteConstraint
    {
        private readonly BlogSupport bs;

        public PageOwnerRouteConstraint()
        {
            bs = new BlogSupport();
        }

        public bool Match(HttpContextBase httpContext, Route route,
            string parameterName, RouteValueDictionary values,
            RouteDirection routeDirection)
        {

            string username = values["username"].ToString();
            return AsyncHelpers.RunSync<bool>(() => bs.Exists(username));
        }
    }

    public class PageNameRouteConstraint : IRouteConstraint
    {
        private readonly BlogSupport bs;

        public PageNameRouteConstraint()
        {
            bs = new BlogSupport();
        }

        public bool Match(HttpContextBase httpContext, Route route,
            string parameterName, RouteValueDictionary values,
            RouteDirection routeDirection)
        {
            string username = values["username"].ToString();
            string blogname = values["blogname"].ToString();
            return AsyncHelpers.RunSync<bool>(() => bs.BlogExists(username, blogname));
        }
    }


}